package com.yunc.modules.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunc.common.utils.R;
import com.yunc.modules.chat.entity.ChatFriends;
import com.yunc.modules.chat.entity.ChatMessages;
import com.yunc.modules.chat.mapper.ChatFriendsMapper;
import com.yunc.modules.chat.service.IChatFriendsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.modules.chat.service.IChatMessagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.yunc.common.utils.ShiroUtils.getUserId;

/**
 * 好友表 service实现
 *
 * @author concong tao
 * @since 2019-03-28
 */
@Service
public class ChatFriendsServiceImpl extends ServiceImpl<ChatFriendsMapper, ChatFriends> implements IChatFriendsService {

    @Autowired
    private IChatMessagesService chatMessagesService;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R saveFriends(ChatFriends chatFriends) {
        Long userId = getUserId();
        // 新增为好友
        chatFriends.setUserId(getUserId());
        // 判断是否已是好友
        ChatFriends record = this.getOne(new QueryWrapper<ChatFriends>()
                .eq("user_id", userId)
                .eq("friend_id", chatFriends.getFriendId()));
        if (record != null) {
            return R.error("已是好友");
        }
        boolean flag = this.save(chatFriends);
        if (flag) {
            // 互相
            ChatFriends friend = new ChatFriends();
            friend.setUserId(chatFriends.getFriendId());
            friend.setFriendId(chatFriends.getUserId());
            friend.setFriendGroupId(chatFriends.getTargetGroupId());
            boolean friendFlag = this.save(friend);
            if (friendFlag) {
                // 互相已经为好友，将此条信息修改为已同意
                ChatMessages messages = chatMessagesService.getOne(new QueryWrapper<ChatMessages>()
                        .eq("from_user_id", chatFriends.getFriendId())
                        .eq("to_user_id", userId));
                if (messages != null) {
                    messages.setStatus("2");
                    chatMessagesService.updateById(messages);
                }
                return R.ok();
            }
        }
        return R.error();
    }
}
